import type { UploadProgressEvent } from "element-plus";

import { Upload } from "@/api/interface/index";
import { PORT1 } from "@/api/config/servicePort";
import http from "@/api";

/**
 * @name 文件上传模块
 */

// 枚举路径
export const enum Path {
  colordemo = "/goods-config/settings/colors/upload",
  certify = "/goods-certify/certify-list/upload-file",
  batchImgSpu = "/goods-archive/batch-images/spu", //批量商品主图
  batchImgDetail = "/goods-archive/batch-images/detail", //批量商品详情图
  batchVedio = "/goods-archive/batch-images/video" //批量商品视频
}

// 用于步骤上传的枚举路径
export const enum UploadStepPath {
  // 商品导入
  goods = "/goods-archive/goods-import/upload",
  // 标签导入
  label = "/km/import/upload"
}

// 图片上传
export const uploadImg = (params: FormData) => {
  return http.post<Upload.ResFileUrl>(PORT1 + `/file/upload/img`, params, { cancel: false });
};

// 视频上传
export const uploadVideo = (params: FormData) => {
  return http.post<Upload.ResFileUrl>(PORT1 + `/file/upload/video`, params, { cancel: false });
};

// 上传附件
export const uploadFiles = (
  path: Path,
  parmas: Record<string, any>,
  data: FormData,
  onProgress?: (progressEvt: UploadProgressEvent) => void
) => {
  let url = `${PORT1}${path}`;

  Object.keys(parmas).forEach(key => {
    if (url.includes("?")) {
      url += `&${key}=${parmas[key]}`;
    } else {
      url += `?${key}=${parmas[key]}`;
    }
    data.append(key, parmas[key]);
  });
  console.log(data, "fas.....");
  return http.post(url, data, {
    headers: { "Content-Type": "multipart/form-data" },
    onUploadProgress: (evt: any) => {
      const progressEvt = evt as UploadProgressEvent;
      progressEvt.percent = evt.total > 0 ? (evt.loaded / evt.total) * 100 : 0;
      onProgress?.(progressEvt);
    },
    loading: false,
    cancel: false
  });
};

// 步骤上传接口
export const uploadStep = (
  path: UploadStepPath,
  params: Record<string, any>,
  formData: FormData,
  onProgress?: (progressEvt: UploadProgressEvent) => void
) => {
  let url = `${PORT1}${path}`;
  Object.keys(params).forEach(key => {
    if (url.includes("?")) {
      url += `&${key}=${params[key]}`;
    } else {
      url += `?${key}=${params[key]}`;
    }
  });
  return http.post(url, formData, {
    headers: { "Content-Type": "multipart/form-data" },
    timeout: Infinity,
    onUploadProgress: (evt: any) => {
      const progressEvt = evt as UploadProgressEvent;
      progressEvt.percent = evt.total > 0 ? (evt.loaded / evt.total) * 100 : 0;
      onProgress?.(progressEvt);
    },
    loading: false,
    cancel: false
  });
};

// 下载文件
export const downloadFile: (url: string, name?: string) => Promise<boolean> = (url, name) => {
  return new Promise(resolve => {
    const xhr = new XMLHttpRequest();
    // `${PORT1}${path}`
    xhr.open("GET", url, true);
    xhr.responseType = "blob";
    xhr.onload = () => {
      if (xhr.status === 200) {
        const URL = window.URL || window.webkitURL || window;
        const link = document.createElement("a");
        link.href = URL.createObjectURL(xhr.response);
        link.download = name ?? Date.now().toString();
        link.click();
        resolve(true);
      }
    };
    xhr.onerror = () => {
      resolve(false);
    };
    xhr.send();
  });
};
